package com.withoutwords.engine.social;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.MalformedURLException;
import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.facebook.android.AsyncFacebookRunner;
import com.facebook.android.AsyncFacebookRunner.RequestListener;
import com.facebook.android.DialogError;
import com.facebook.android.Facebook;
import com.facebook.android.Facebook.DialogListener;
import com.facebook.android.FacebookError;
import com.withoutwords.engine.MyInfo;
import com.withoutwords.engine.social.listeners.ICurrentUserInfoListener;
import com.withoutwords.engine.social.listeners.ISocialFriendListListener;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;

public class FacebookController implements ISocialNetworkController {
	 final String APP_ID = "190851861041135";
	 Facebook facebook = new Facebook(APP_ID);
	 AsyncFacebookRunner fbRunner = new AsyncFacebookRunner(facebook);
	 private SharedPreferences mPrefs;
	
	 String userEmail;
	 String userFB_id;
	//request login to social network
		public void requestLogin(Activity Act)
		{
			if(!isLoggenIn(Act)) {

	            facebook.authorize(Act, new String[] {}, new DialogListener() {
	                @Override
	                public void onComplete(Bundle values) {
	                	
	                    SharedPreferences.Editor editor = mPrefs.edit();
	                    editor.putString("access_token", facebook.getAccessToken());
	                    editor.putLong("access_expires", facebook.getAccessExpires());
	                    editor.commit();
	                }
	    
	                @Override
	                public void onFacebookError(FacebookError error) {}
	    
	                @Override
	                public void onError(DialogError e) {}
	    
	                @Override
	                public void onCancel() {}
	            });
	        }
		}
		
		//callback for login request
		public boolean onLoginCallback(int requestCode,int resultCode,Intent data)
		{
			facebook.authorizeCallback(requestCode, resultCode, data);
			 String error = data.getStringExtra("error");
             return (error == null) ;
		}
		
		//share data on social network
		public void share(Context context,String sharedata)
		{
			Bundle params = new Bundle();
		    params.putString("description", sharedata);
		    params.putString("caption", "My Caption");
          //  params.putString("description", getString(R.string.app_desc));
           // params.putString("picture", Utility.HACK_ICON_URL);
            params.putString("name", "My Name");
            params.putString("link", "www.google.com");
			 facebook.dialog(context, "feed",params,new DialogListener() {
	                @Override
	                public void onComplete(Bundle values) {
	                  
	                }
	    
	                @Override
	                public void onFacebookError(FacebookError error) {}
	    
	                @Override
	                public void onError(DialogError e) {}
	    
	                @Override
	                public void onCancel() {}
	            });
		}
		
		//invite friends..this process includes selecting friends dialog
		public void inviteFriends(Context context,String invitationString)
		{
			Bundle params = new Bundle();
		    params.putString("message", invitationString);
			 facebook.dialog(context, "apprequests",params,new DialogListener() {
	                @Override
	                public void onComplete(Bundle values) {
	                	Log.e("app request complete", "success");
	                  
	                }
	    
	                @Override
	                public void onFacebookError(FacebookError error) {
	                	Log.e("app request complete", "FacebookError");
	                }
	    
	                @Override
	                public void onError(DialogError e) {
	                	Log.e("app request complete", "DialogError");
	                }
	    
	                @Override
	                public void onCancel() {
	                	Log.e("app request complete", "onCancel");
	                }
	            });
		}
		
		private ArrayList<SocialUser> parseJsonFriendList(String jsonResponse)
		{
			ArrayList<SocialUser> friendsArray = new ArrayList<SocialUser>();
			try {
				JSONObject response = new JSONObject(jsonResponse);
				JSONArray jsonFriendList = response.getJSONArray("data");
				
				for(int i=0 ;i < jsonFriendList.length() ; i++)
				{
					JSONObject jObj = jsonFriendList.getJSONObject(i);
					SocialUser sf = new SocialUser();
					sf.network = SocialNetwork.Facebook;
					sf.SocialID = jObj.getString("id");
					sf.Name = jObj.getString("name");
					friendsArray.add(sf);
				}
				
				
				//return friendsArray;
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				
			}
			return friendsArray;
		}
		//read friends
		public ArrayList<SocialUser> readFriendList(boolean bGameUsersOnly)
		{
			//return null;
			try {
				String jsonFriends = facebook.request("me/friends");
				return parseJsonFriendList(jsonFriends);
			} catch (MalformedURLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return null;
		}

		@Override
		public void readFriendList(final ISocialFriendListListener listener,boolean bGameUsersOnly) {
		fbRunner.request("me/friends", new RequestListener() {
			
			@Override
			public void onMalformedURLException(MalformedURLException e, Object state) {
				// TODO Auto-generated method stub
				listener.onError("");
			}
			
			@Override
			public void onIOException(IOException e, Object state) {
				// TODO Auto-generated method stub
				listener.onError("");
			}
			
			@Override
			public void onFileNotFoundException(FileNotFoundException e, Object state) {
				// TODO Auto-generated method stub
				listener.onError("");
			}
			
			@Override
			public void onFacebookError(FacebookError e, Object state) {
				// TODO Auto-generated method stub
				listener.onError("");
			}
			
			@Override
			public void onComplete(String response, Object state) {
				// TODO Auto-generated method stub
				
				listener.onFriendListRecieved(parseJsonFriendList(response));
			}
		});
			
		}
		
		public boolean isLoggenIn(Activity Act)
		{
			/*
	         * Get existing access_token if any
	         */
			//Context context ;
			mPrefs = Act.getApplication().getSharedPreferences("Facebook", Activity.MODE_PRIVATE);
	     //   mPrefs = Act.getPreferences(Activity.MODE_PRIVATE);
	        String access_token = mPrefs.getString("access_token", null);
	        long expires = mPrefs.getLong("access_expires", 0);
	        if(access_token != null) {
	            facebook.setAccessToken(access_token);
	            facebook.extendAccessTokenIfNeeded(Act, null);
	        }
	        if(expires != 0) {
	            facebook.setAccessExpires(expires);
	        }
	        
	        /*
	         * Only call authorize if the access_token has expired.
	         */
	        return facebook.isSessionValid();
		}

		@Override
		public void getCurrentUserInfo(final ICurrentUserInfoListener listener) {
			fbRunner.request("me", new RequestListener() {
				
				@Override
				public void onMalformedURLException(MalformedURLException e, Object state) {
					// TODO Auto-generated method stub
					listener.onError("");
				}
				
				@Override
				public void onIOException(IOException e, Object state) {
					// TODO Auto-generated method stub
					listener.onError("");
				}
				
				@Override
				public void onFileNotFoundException(FileNotFoundException e, Object state) {
					// TODO Auto-generated method stub
					listener.onError("");
				}
				
				@Override
				public void onFacebookError(FacebookError e, Object state) {
					// TODO Auto-generated method stub
					listener.onError("");
				}
				
				@Override
				public void onComplete(String jsonResponse, Object state) {
					// TODO Auto-generated method stub
					MyInfo me = new MyInfo();
					try {
					JSONObject jObj = new JSONObject(jsonResponse);
						SocialUser sf = new SocialUser();
						sf.network = SocialNetwork.Facebook;
						sf.SocialID = jObj.getString("id");
						sf.Name = jObj.getString("name");
							
						me.setSocialUser(sf);
						me.setEmail(jObj.getString("email"));
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
						
					}
					listener.onCurrentUserInfoRecieved(me);
				}
			});
			
		}

		

		
		

}
